//
//  Int.swift
//  eval
//
//  Created by hengchengfei on 15/9/6.
//  Copyright © 2015年 chengfeisoft. All rights reserved.
//
import UIKit

public extension NSDate {
    
    /**
     日期转换为相应格式的字符串
    */
    func toString(format:String) -> String {
        let dateFormatter = NSDateFormatter()
        dateFormatter.timeZone = NSTimeZone.localTimeZone()
        dateFormatter.dateFormat = format
        
        return dateFormatter.stringFromDate(self)
    }
    
    /**
     是否为今天（只比较日期，不比较时分秒）
    */
    func isToday() -> Bool {
        let date = NSDate()
        
        if self.toString("yyyyMMdd") == date.toString("yyyyMMdd") {
            return true
        }
        return false
    }
    
    /**
     取得与当前时间的间隔差
    */
    func calTimeAfterNow() -> String {
        let timeInterval = NSDate().timeIntervalSinceDate(self)
        if timeInterval < 0 {
            return "刚刚"
        }
        
        let interval = fabs(timeInterval)
        
        let i60 = interval/60
        let i3600 = interval/3600
        let i86400 = interval/86400
        let i2592000 = interval/2592000
        let i31104000 = interval/31104000
        
        var time:String!
        
        if i3600 < 1 {
            let s = NSNumber(double: i60).integerValue
            if s == 0 {
                time = "刚刚"
            }else{
                time = "\(s)分钟前"
            }
        }else if i86400 < 1 {
            let s = NSNumber(double:i3600).integerValue
            time = "\(s)小时前"
        }else if i2592000 < 1 {
            let s = NSNumber(double:i86400).integerValue
            time = "\(s)天前"
        }else if i31104000 < 1 {
            let s = NSNumber(double:i2592000).integerValue
            time = "\(s)个月前"
        }else  {
            let s = NSNumber(double:i31104000).integerValue
            time = "\(s)年前"
        }
        return time
    }
}
